﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using BUS;
using System.Data.SqlClient;
using DTO;
using System.Data.DataSetExtensions;
using System.Linq;
namespace GPBenhLanh
{
    public partial class frmDKDVGuiMau : DevExpress.XtraEditors.XtraForm
    {
        SqlConnection _conPK;
        public SqlConnection conPK
        {
            get
            {
                return _conPK;
            }
            set
            {
                if (_conPK == value)
                    return;
                _conPK = value;
            }
        }

        SqlConnection _conGPB;
        public SqlConnection conGPB
        {
            get
            {
                return _conGPB;
            }
            set
            {
                if (_conGPB == value)
                    return;
                _conGPB = value;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public frmDKDVGuiMau()
        {
            InitializeComponent();
        }
        
        /// <summary>
        /// 
        /// </summary>
        /// <param name="conn"></param>
        public frmDKDVGuiMau(SqlConnection conn)
        {
            InitializeComponent();
            _conPK = conn;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="conn"></param>
        /// <param name="conn2"></param>
        public frmDKDVGuiMau(SqlConnection conn, SqlConnection conn2)
        {
            InitializeComponent();
            _conPK = conn;
            _conGPB = conn2;
        }

        DataTable dtMDBVNgoai;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRemove_Click(object sender, EventArgs e)
        {
            DataTable dtDvuBV = (DataTable)gridDSDonViNoiVien.DataSource;

            DataRow drAdd   = dtDvuBV.NewRow();
            DataRow dr      = viewDVKhoaGPB.GetDataRow(viewDVKhoaGPB.FocusedRowHandle);
            if (dr != null)
            {
                drAdd["MaDonVi"] = dr["MaDonVi"];
                drAdd["TenDonVi"] = dr["TenDonVi"];
                //add vao sanh dich vu cua benh vien
                dtDvuBV.Rows.Add(drAdd);

                //remove dong da add vao ds dich vu cua don vi
                DataTable dtDVuDVi = (DataTable)gridDVGMKhoaGPB.DataSource;
                int index = dtDVuDVi.Rows.IndexOf(dr);
                dtDVuDVi.Rows.RemoveAt(index);

                //sort lai danh sach thuoc cua benh vien
                dtDvuBV.DefaultView.Sort = "TenDonVi ASC";
                dtDvuBV = dtDvuBV.DefaultView.ToTable(true);
                gridDSDonViNoiVien.DataSource = dtDvuBV;

                //sort lai danh sach thuoc cu benh vien
                dtDVuDVi.DefaultView.Sort = "TenDonVi ASC";
                dtDVuDVi = dtDVuDVi.DefaultView.ToTable(true);
                gridDVGMKhoaGPB.DataSource = dtDVuDVi;                
            }          
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object sender, EventArgs e)
        {
            DataTable dtDVKhoaGPB = (DataTable)gridDVGMKhoaGPB.DataSource;

            DataRow drAdd = dtDVKhoaGPB.NewRow();
            DataRow dr = viewDVBV.GetDataRow(viewDVBV.FocusedRowHandle);
            if (dr != null)
            {
                drAdd["MaDonVi"] = dr["MaDonVi"];
                drAdd["TenDonVi"] = dr["TenDonVi"];

                drAdd["LoaiDV"] = 1;
                drAdd["NgungSD"] = 0;
                string select = "MaDonVi = '" + drAdd["MaDonVi"].ToString() + "'";
                DataRow[] arr = dtDVKhoaGPB.Select(select);
                if (arr.Length <= 0)
                {
                    //add danh sach dich vu cua don vi
                    dtDVKhoaGPB.Rows.Add(drAdd);
                }
                //remove dong da add vao ds dich vu cua don vi
                DataTable dtDVuBV = (DataTable)gridDSDonViNoiVien.DataSource;
                int index = dtDVuBV.Rows.IndexOf(dr);
                dtDVuBV.Rows.RemoveAt(index);

                //sort lai danh sach thuoc cu benh vien
                dtDVuBV.DefaultView.Sort = "TenDonVi ASC";
                dtDVuBV = dtDVuBV.DefaultView.ToTable(true);
                gridDSDonViNoiVien.DataSource = dtDVuBV;

                //sort lai danh sach thuoc cu benh vien
                dtDVKhoaGPB.DefaultView.Sort = "TenDonVi ASC";
                dtDVKhoaGPB = dtDVKhoaGPB.DefaultView.ToTable(true);
                gridDVGMKhoaGPB.DataSource = dtDVKhoaGPB;
                
            }              
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmDangKyThuoc_Load(object sender, EventArgs e)
        {
            if (conPK.State != ConnectionState.Open)
            {
                MessageBox.Show(hensu.sConnFaile, "Thông Báo");
                return;
            }
            DataTable dtDViBV = new DataTable();
            dtDViBV = DonVi_BUS.GetDonViAll(conPK);
            lblStatus.Visible = false;
            ///load danh muc don vi cua benh vien
            DataTable dtMDDVBV = new DataTable();
            gridDSDonViNoiVien.DataSource = dtDViBV;

            ///load danh sach don vi gui mau cua kho gpb         
            DataTable dtMDDVGuiKhoa = new DataTable();
            dtMDDVGuiKhoa = DonVi_BUS.GetDonViDaAdd(1);
            gridDVGMKhoaGPB.DataSource = dtMDDVGuiKhoa;

            for (int i = 0; i < dtMDDVGuiKhoa.Rows.Count; i++)
            {
                for (int j = 0; j < dtDViBV.Rows.Count; j++)
                {
                    if (dtMDDVGuiKhoa.Rows[i]["MaDonVi"].Equals(dtDViBV.Rows[j]["MaDonVi"]))
                    {
                        dtDViBV.Rows.RemoveAt(j);
                    }
                }
            }
            //load data to tab benh vien ben ngoai            
            dtMDBVNgoai = DonVi_BUS.GetDonViDaAdd(2);
            gridDSDVNgoaiVien.DataSource = dtMDBVNgoai;
        }
             

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private DataTable Create_utb_TTT_DMThuoc()
        {
            DataTable SaveData = new DataTable();
            /// Add the columns to the SaveData DataTable
            SaveData.Columns.Add("MaDonVi", typeof(string));            
            SaveData.Columns.Add("TenDonVi", typeof(string));
            SaveData.Columns.Add("LoaiDV", typeof(int));
            SaveData.Columns.Add("NgungSD", typeof(Boolean));           
            return SaveData;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dtSaveDel"></param>
        /// <returns></returns>
        private DataTable SetData_GPB_DVGUIMAU(DataTable dtSaveDel)
        {
            // create table utb_TTT_DMThuoc
            DataTable SaveData = new DataTable("GPB_DVGUIMAU");
            SaveData = Create_utb_TTT_DMThuoc();
            /// Create a new row and add data to new row
            DataRow Row;
            foreach (DataRow RowS in dtSaveDel.Rows)
            {
                Row = SaveData.NewRow();
                Row["MaDonVi"] = RowS["MaDonVi"];
                Row["TenDonVi"] = RowS["TenDonVi"];
                Row["LoaiDV"] = RowS["LoaiDV"];
                Row["NgungSD"] = RowS["NgungSD"];             
               
                /// Add the row to the SaveData DataTable
                SaveData.Rows.Add(Row);
            }
            return SaveData;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="conn"></param>
        /// <param name="data"></param>
        private void insertSqlBulkCopy(SqlConnection conn, DataTable data)
        {
            if (data != null || data.Rows.Count > 0)
            {
                /// Insert to database by sqlBulkcopy from databale SaveData
                using (SqlBulkCopy s = new SqlBulkCopy(conn))
                {
                    s.DestinationTableName = "GPB_DVGUIMAU";

                    foreach (var column in data.Columns)
                    {
                        s.ColumnMappings.Add(column.ToString(), column.ToString());
                    }
                    s.WriteToServer(data);                  
                }
            }
        }

        /// <summary>
        /// Bulk save data
        /// </summary>
        /// <param name="sender"> </param>
        /// <param name="e"> </param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            ///luu vao database
            DataTable dtDMDVKhoaGPB = new DataTable();
            dtDMDVKhoaGPB = (DataTable)gridDVGMKhoaGPB.DataSource;
            DataTable dtSave = dtDMDVKhoaGPB.GetChanges(DataRowState.Added);

            if (dtSave != null)
            {
                /// Delete data in datatalbe GPB_DVGUIMAU by MaDVi 
                string MaDVi = "";
                string TenDV = "";
                int LoaiDV = 1;
                bool Xoa = false;
                DonVi_BUS.delAllDMThuocKhoa(1);
                for (int i = 0; i < dtDMDVKhoaGPB.Rows.Count; i++)
                {
                    MaDVi = dtDMDVKhoaGPB.Rows[i]["MaDonVi"].ToString();
                    TenDV = dtDMDVKhoaGPB.Rows[i]["TenDonVi"].ToString().ToUpper();
                    LoaiDV = int.Parse(dtDMDVKhoaGPB.Rows[i]["LoaiDV"].ToString());
                    Xoa = bool.Parse(dtDMDVKhoaGPB.Rows[i]["NgungSD"].ToString());

                    DonVi_BUS.insDMThuocKhoa(MaDVi, TenDV, LoaiDV, Xoa);
                }
               
                MessageBox.Show("Đã lưu xong.!","Thông báo");
                frmDangKyThuoc_Load(sender, e);
            }
            else
            {
                lblStatus.Visible = true;
                lblStatus.Text = "Không có dữ liệu thay đổi.!";
            }
        }

        private DataTable ComputateDiff(DataTable newVersion, DataTable oldVersion)
        {
            var qry1 = newVersion.AsEnumerable().Select(a => new { MobileNo = a["MaDonVi"].ToString() });
            var qry2 = oldVersion.AsEnumerable().Select(b => new { MobileNo = b["MaDonVi"].ToString() });

            var exceptAB = qry1.Except(qry2);

            DataTable dtMisMatch = (from a in newVersion.AsEnumerable()
                                    join ab in exceptAB on a["MaDonVi"].ToString() equals ab.MobileNo
                                    select a).CopyToDataTable();

            // var tableAIds = newVersion.AsEnumerable().Select(row => (string)row["MaDonVi"]);
            //var tableBIds = oldVersion.AsEnumerable().Select(row => (string)row["MaDonVi"]);
            //var resultantIds = tableAIds.Except(tableBIds);
            //DataTable diff =  from myRow in oldVersion.AsEnumerable()
            //          join rIDS resultantIds in myRow.Field<string>("MaDonVi") equals rIDS
            //          select myRow).CopyToDataTable();
            return dtMisMatch;
        }

        private void btnLuuNgoaiVien_Click(object sender, EventArgs e)
        {
            ///luu vao database
            DataTable dtDMBVNew = new DataTable();
            dtDMBVNew = (DataTable)gridDSDVNgoaiVien.DataSource;
            //DataTable dtSave = dtDMDVKhoaGPB.GetChanges(DataRowState.Added);
            DataTable dtSave;
            //if (dtMDBVNgoai != null)
            //{
            //    dtSave = ComputateDiff(dtDMBVNew, dtMDBVNgoai);
            //}
            //else
            //{
            //    dtSave = dtDMBVNew;
            //}
            dtSave = dtDMBVNew;
            if (dtSave != null)
            {
                /// Delete data in datatalbe GPB_DVGUIMAU by MaDVi 
                string MaDVi = "";
                string TenDV = "";
                int LoaiDV = 1;
                bool Xoa = false;
                DonVi_BUS.delAllDMThuocKhoa(2);
                for (int i = 0; i < dtSave.Rows.Count; i++)
                {
                    MaDVi = dtSave.Rows[i]["MaDonVi"].ToString();
                    TenDV = dtSave.Rows[i]["TenDonVi"].ToString().ToUpper();
                    LoaiDV = 2;
                    if (dtSave.Rows[i]["NgungSD"].ToString() != "")
                    {
                        Xoa = bool.Parse(dtSave.Rows[i]["NgungSD"].ToString());
                    }
                 
                    DonVi_BUS.insDMThuocKhoa(MaDVi, TenDV, LoaiDV, Xoa);
                }

                MessageBox.Show("Đã lưu xong.!", "Thông báo");
                frmDangKyThuoc_Load(sender, e);
            }
            else
            {
                lblStatus.Visible = true;
                lblStatus.Text = "Không có dữ liệu thay đổi.!";
            }
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            ///load danh sach don vi gui mau cua kho gpb         
            DataTable dtMDDVGuiKhoa = new DataTable();
            dtMDDVGuiKhoa = DonVi_BUS.GetDonViDaAdd(2);
            gridDSDVNgoaiVien.DataSource = dtMDDVGuiKhoa;
        }

    }
}